/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormProduto.java
 *
 * Created on 29/08/2011, 18:14:46
 */
package javalee.forms;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javalee.util.Uteis;
import javalee.maps.Maquina;
import javalee.maps.Produto;
import javalee.dao.ProdutoDAO;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Thiago

 */
public class FormProduto extends javax.swing.JFrame {
    
      private ProdutoDAO prodDAO;
      private FormListMaquinas frmMaq;
      private formComponentes frmComponente;
        
      

    /** Creates new form FormProduto */
    public FormProduto() {
        initComponents();
        prodDAO = new ProdutoDAO();
        frmMaq = new FormListMaquinas(txtmaquina);
        frmComponente = new formComponentes();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaProd = new javax.swing.JTable();
        txtConsulta = new javax.swing.JTextField();
        txtdescricao = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtid = new javax.swing.JTextField();
        btnOk = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        txtmaquina = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btnMaq = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        btnComponentes = new javax.swing.JButton();
        cmbOrigem = new javax.swing.JComboBox();
        /*javax.swing.text.MaskFormatter mf = null;
        try{
            mf = new javax.swing.text.MaskFormatter("####");
        }
        catch(java.text.ParseException p){
            p.printStackTrace();
        }*/
        txtquant = new javax.swing.JFormattedTextField(java.text.NumberFormat.getInstance());
        /*javax.swing.text.MaskFormatter mf2 = null;
        try{
            mf2 = new javax.swing.text.MaskFormatter("####");
        }
        catch(java.text.ParseException p){
            p.printStackTrace();
        }*/
        txttempo = new javax.swing.JFormattedTextField(java.text.NumberFormat.getInstance());
        jLabel8 = new javax.swing.JLabel();
        txtValorCompra = new javax.swing.JTextField();
        txtValorVenda = new javax.swing.JTextField();
        txtNivelCritico = new javax.swing.JTextField();
        txtLote = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtIpi = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();

        setTitle("Formulario de Produto");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        tabelaProd.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "ID", "Descrição", "Tempo", "Origem", "Quantidade", "Nome Maquina", "ID Maquina", "Valor Venda", "Valor Compra", "Nível Crítico", "Lote", "IPI"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Float.class, java.lang.Float.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaProd.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tabelaProdMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaProd);

        txtConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtConsultaKeyReleased(evt);
            }
        });

        jLabel1.setText("Descrição : ");

        jLabel2.setText("Origem : ");

        jLabel3.setText("Quantidade : ");

        jLabel4.setText("ID : ");

        txtid.setEnabled(false);
        txtid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtidActionPerformed(evt);
            }
        });

        btnOk.setLabel("Salvar");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        jButton5.setText("Fechar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        txtmaquina.setEditable(false);
        txtmaquina.setEnabled(false);

        jLabel5.setText("Tempo : ");

        jLabel6.setText("ID Maquina : ");

        btnMaq.setText("Maquinas");
        btnMaq.setEnabled(false);
        btnMaq.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMaqActionPerformed(evt);
            }
        });

        jLabel7.setText("horas");

        btnComponentes.setBackground(new java.awt.Color(153, 255, 153));
        btnComponentes.setText("Componentes");
        btnComponentes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnComponentesActionPerformed(evt);
            }
        });

        cmbOrigem.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--", "M", "I", "F" }));
        cmbOrigem.setToolTipText("Matéria-prima, \nIntermediário, \nFinal");
        cmbOrigem.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbOrigemItemStateChanged(evt);
            }
        });

        /*
        txtquant.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(mf, mf));
        */

        /*
        txttempo.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(mf2, mf2));
        txttempo.setEnabled(false);
        */

        jLabel8.setText("Valor Compra/Venda:");

        txtValorCompra.setName("txtValorCompra"); // NOI18N

        txtValorVenda.setName("txtValorVenda"); // NOI18N

        txtNivelCritico.setName("txtNivelCritico"); // NOI18N

        txtLote.setName("txtLote"); // NOI18N

        jLabel9.setText("Nível Crítico:");

        jLabel10.setText("Lote:");

        txtIpi.setName("txtValorVenda"); // NOI18N

        jLabel11.setText("IPI:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtConsulta, javax.swing.GroupLayout.DEFAULT_SIZE, 1025, Short.MAX_VALUE)
                        .addGap(354, 354, 354))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel6)
                                    .addComponent(btnNovo))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnExcluir)
                                .addGap(140, 140, 140)
                                .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(219, 219, 219)
                                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 462, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGap(23, 23, 23)
                                                .addComponent(jLabel2))
                                            .addGroup(layout.createSequentialGroup()
                                                .addGap(45, 45, 45)
                                                .addComponent(jLabel4)))
                                        .addGap(26, 26, 26)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(txtmaquina, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
                                            .addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(cmbOrigem, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addGap(29, 29, 29)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                    .addComponent(jLabel3)
                                                    .addComponent(jLabel1))
                                                .addGap(8, 8, 8)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addComponent(txtquant, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(jLabel9)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(txtNivelCritico, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGap(6, 6, 6)
                                                        .addComponent(jLabel10)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(txtLote, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                    .addComponent(txtdescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addComponent(jLabel8)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(txtValorCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(txtValorVenda, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
                                                        .addComponent(jLabel11)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(txtIpi, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGap(128, 128, 128))
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addComponent(jLabel5)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(txttempo, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(jLabel7)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 332, Short.MAX_VALUE))))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(btnMaq, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(52, 52, 52)
                                                .addComponent(btnComponentes)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 717, Short.MAX_VALUE))))
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 1156, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(90, 90, 90)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(txtid, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtdescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel8)
                        .addComponent(txtValorCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtValorVenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtIpi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel11)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(cmbOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtquant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNivelCritico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtLote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(jLabel10)
                    .addComponent(jLabel5)
                    .addComponent(txttempo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtmaquina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnMaq)
                    .addComponent(btnComponentes))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnExcluir)
                    .addComponent(btnOk)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        txtConsulta.getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
 if(ValidarForm()){
    try{
        
     int row = tabelaProd.getSelectedRow();
        Produto prod = new Produto();
        prod.setDescricao(txtdescricao.getText());
        if(cmbOrigem.getSelectedIndex()>=2){
        prod.setIdMaquina(new Maquina(Integer.parseInt(txtmaquina.getText())));
        }
        else{
            prod.setIdMaquina(new Maquina());
        }
        prod.setOrigem(cmbOrigem.getSelectedItem().toString().charAt(0));
        prod.setQtdade(Integer.parseInt(txtquant.getText()));
        prod.setTempo(Integer.parseInt(txttempo.getText()));
        
        prod.setValorCompra(Float.parseFloat(txtValorCompra.getText()));
        prod.setValorVenda(Float.parseFloat(txtValorVenda.getText()));
        prod.setNivelCritico(Short.parseShort(txtNivelCritico.getText()));
        prod.setLote(Short.parseShort(txtLote.getText()));
        prod.setIpi(Float.parseFloat(txtIpi.getText()));
        
        if(row == -1){
            
            if (prodDAO.cadastrar(prod)) {
                JOptionPane.showMessageDialog(null, "Produto cadastrado.");
                if(cmbOrigem.getSelectedItem().toString().charAt(0)!= 'M'){
                   frmComponente.setProduto(new Produto(prodDAO.getUltimoID()));
                   frmComponente.setVisible(true); 
                }
                
                //txtMaquina.setText("");
            } else {
                JOptionPane.showMessageDialog(null, "Problema ao cadastrar Produto.");
            }
        }
        else{
            prod.setId(Integer.parseInt(txtid.getText()));
            if (prodDAO.alterar(prod)) {
                JOptionPane.showMessageDialog(null, "Produto alterado.");
            } else {
                JOptionPane.showMessageDialog(null, "Problema ao alterar produto.");
            }
        }
 }

     catch (Exception e) {
        System.out.println(e.toString());
    }
 preencheDados();
 limpaDados();
 }
}//GEN-LAST:event_btnOkActionPerformed

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
dispose();
}//GEN-LAST:event_jButton5ActionPerformed

private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
limpaDados();
ProdutoEstaSelecionado(false);
tabelaProd.clearSelection();
}//GEN-LAST:event_btnNovoActionPerformed

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
preencheDados();
ProdutoEstaSelecionado(false);
}//GEN-LAST:event_formWindowOpened

private void btnMaqActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMaqActionPerformed
 frmMaq.setVisible(true);
}//GEN-LAST:event_btnMaqActionPerformed

private void txtidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtidActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtidActionPerformed

private void txtConsultaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtConsultaKeyReleased
    if(evt.getKeyCode()==10){
        preencheDados();
    }
}//GEN-LAST:event_txtConsultaKeyReleased

private void tabelaProdMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaProdMouseReleased
 int row = tabelaProd.getSelectedRow();
 ProdutoEstaSelecionado(true);
 
    DefaultTableModel tableModel = (DefaultTableModel)tabelaProd.getModel(); 
    if(tableModel.getValueAt(row, 3).toString().charAt(0) == 'M'){
      btnComponentes.setEnabled(false);
      btnMaq.setEnabled(false);
      txtmaquina.setEnabled(false);
    }
    else{
      btnComponentes.setEnabled(true);
      btnMaq.setEnabled(true);
      txtmaquina.setEnabled(true);
     }
    txtid.setText(tableModel.getValueAt(row, 0).toString());
    txtdescricao.setText(tableModel.getValueAt(row, 1).toString());
    txttempo.setText(tableModel.getValueAt(row, 2).toString());
    cmbOrigem.setSelectedItem(tableModel.getValueAt(row, 3).toString());
    txtquant.setText(tableModel.getValueAt(row, 4).toString());
    txtmaquina.setText(tableModel.getValueAt(row, 6).toString());
    txtValorCompra.setText(tableModel.getValueAt(row, 7).toString());
    txtValorVenda.setText(tableModel.getValueAt(row, 8).toString());
    txtNivelCritico.setText(tableModel.getValueAt(row, 9).toString());
    txtLote.setText(tableModel.getValueAt(row, 10).toString());
    txtIpi.setText(tableModel.getValueAt(row, 11).toString());
    // TODO add your handling code here:
}//GEN-LAST:event_tabelaProdMouseReleased

private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
     int row = tabelaProd.getSelectedRow();
    
    DefaultTableModel tableModel = (DefaultTableModel)tabelaProd.getModel();  
    Produto prod = new Produto(Integer.parseInt(tableModel.getValueAt(row, 0).toString()));
    
    if(JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir o produto?","Confirmação!",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
        prodDAO.excluir(prod);
        limpaDados();
        JOptionPane.showMessageDialog(null, "Produto excluído com sucesso.");
        preencheDados();
    }
    
    // TODO add your handling code here:
}//GEN-LAST:event_btnExcluirActionPerformed

private void btnComponentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnComponentesActionPerformed
    int row = tabelaProd.getSelectedRow();
    if (row != -1){
    DefaultTableModel tableModel = (DefaultTableModel)tabelaProd.getModel();
    
    frmComponente.setProduto(new Produto(Integer.parseInt(tableModel.getValueAt(row, 0).toString())));
    frmComponente.setVisible(true);
 
    }
}//GEN-LAST:event_btnComponentesActionPerformed

private void cmbOrigemItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbOrigemItemStateChanged
    if(cmbOrigem.getSelectedIndex()<=1){
      txtmaquina.setText("");
      btnMaq.setEnabled(false);
      txtmaquina.setEnabled(false);
      txttempo.setText("0");
      txttempo.setEnabled(false);
      jLabel5.setEnabled(false);
      jLabel7.setEnabled(false);
    }
    else{
      btnMaq.setEnabled(true);
      txtmaquina.setEnabled(true);
      txttempo.setEnabled(true);
      jLabel5.setEnabled(true);
      jLabel7.setEnabled(true);
     }
    // TODO add your handling code here:
}//GEN-LAST:event_cmbOrigemItemStateChanged

private void limpaDados(){
    txtConsulta.setText("");
    txtdescricao.setText("");
    txtid.setText("");
    txtmaquina.setText("");
    cmbOrigem.setSelectedIndex(0);
    txtquant.setText("");
    txttempo.setText("");
    btnMaq.setEnabled(false);
    txtmaquina.setEnabled(false);
    txtValorCompra.setText("");
    txtValorVenda.setText("");
    txtNivelCritico.setText("");
    txtLote.setText("");
    txtIpi.setText("");
}

private void ProdutoEstaSelecionado(boolean travar){
    btnExcluir.setEnabled(travar);
    btnComponentes.setEnabled(travar);
    cmbOrigem.setEnabled(!travar);
}

 
private void preencheDados(){
     if(!Uteis.validaCampoTexto(txtConsulta)){
            JOptionPane.showMessageDialog(null,"Campo de pesquisa está incorreto.");
        }
        else{
     //Trago a lista de maquinas do banco
     ArrayList<Produto> lista = prodDAO.consultar(txtConsulta.getText().toString());
     tabelaProd.removeAll();
     
     //Pego o TableModel do componente JTable
     DefaultTableModel tableModel = (DefaultTableModel)tabelaProd.getModel();  
     //Limpo os dados do componente
     tableModel.setNumRows(0);
     
     //Passo pela lista de Maquinas, inserindo no JTable
     for(Iterator<Produto> it = lista.iterator(); it.hasNext();){
        Produto p = (Produto)it.next();
        tableModel.addRow(new Object[]{
            p.getId(),
            p.getDescricao(),
            p.getTempo(),
            p.getOrigem(),
            p.getQtdade(),
            p.getIdMaquina().getDescricao(),
            p.getIdMaquina().getId(),
            p.getValorCompra(),
            p.getValorVenda(),
            p.getNivelCritico(),
            p.getLote(),
            p.getIpi()
        });     
    }   
     }
}
private boolean ValidarForm()
    {
        boolean valido = true;
        try{
        if(txtdescricao.getText().trim().length()<2)
        {
            valido = false;
            JOptionPane.showMessageDialog(null,"Descrição do produto inválida.");
        }
        else if(!Uteis.validaCampoTexto(txtdescricao)){
            valido = false;
            JOptionPane.showMessageDialog(null,"Descrição do Produto inválida.");
        }
        if(cmbOrigem.getSelectedIndex()==0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Selecione Origem.");
        }
        if(txtquant.getText().trim().equals("")){
            valido = false;
            JOptionPane.showMessageDialog(null,"Digite uma quantidade.");
        }
        else if(Integer.parseInt(txtquant.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Quantidade deve ser um valor positivo.");
        }
        else if(Float.parseFloat(txtValorCompra.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Valor da compra deve ser um valor positivo.");
        }else if(Float.parseFloat(txtValorVenda.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Valor da venda deve ser um valor positivo.");
        }else if(Float.parseFloat(txtIpi.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"IPI deve ser um valor positivo.");
        }
        else if(Integer.parseInt(txtNivelCritico.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Nível crítico deve ser um valor positivo.");
        }
        else if(Integer.parseInt(txtLote.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Lote deve ser um valor positivo.");
        }
        if(txttempo.getText().trim().equals("")){
            valido = false;
            JOptionPane.showMessageDialog(null,"Digite um valor para tempo.");
        }
        else if(Integer.parseInt(txttempo.getText())<0){
            valido = false;
            JOptionPane.showMessageDialog(null,"Tempo deve ser um valor positivo.");
        }
        if(cmbOrigem.getSelectedIndex()>=2 && txtmaquina.getText().trim().equals("")){
            valido = false;
            JOptionPane.showMessageDialog(null,"Selecione uma Máquina.");
        }
        }catch(Exception ex){
            valido = false;
        }
        return valido;
    }



    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FormProduto().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnComponentes;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnMaq;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnOk;
    private javax.swing.JComboBox cmbOrigem;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelaProd;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JTextField txtIpi;
    private javax.swing.JTextField txtLote;
    private javax.swing.JTextField txtNivelCritico;
    private javax.swing.JTextField txtValorCompra;
    private javax.swing.JTextField txtValorVenda;
    private javax.swing.JTextField txtdescricao;
    private javax.swing.JTextField txtid;
    private javax.swing.JTextField txtmaquina;
    private javax.swing.JFormattedTextField txtquant;
    private javax.swing.JFormattedTextField txttempo;
    // End of variables declaration//GEN-END:variables
}
